<?php

namespace app\api\home;

use app\common\controller\Common;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class Base extends common
{
    protected $uid;
    protected $username;
    protected $eid;

    //验证token
    public function initialize()
    {
        //获取Authonrization
        if (!isset($_SERVER['HTTP_AUTHORIZATION'])) {
            return_ajax('999999', '缺少token');
        }
        $auth = $_SERVER['HTTP_AUTHORIZATION'];

        //截取token
        $token = substr($auth, 7);

        try {

//            JWT::$leeway = 60;//当前时间减去60，把时间留点余地
            $key = new Key(env('redis_jwt_key'), 'HS256');
            $decode = JWT::decode($token, $key);
            $uid = $decode->data->uid;
//            $mobile = $decode->data->mobile;
            $username = $decode->data->username;

            $data = redis()->get('userInfo:'.$uid);
            $data = (array)json_decode($data);

            if (empty($data)) {
                return_ajax('666666', '账号已推出登录');
            }

            $this->uid = $uid;
            $this->username = $username;

        } catch (\Firebase\JWT\SignatureInvalidException $e) {  //签名不正确
            return_ajax('999999', 'token无效!', $e->getMessage());
        } catch (\Firebase\JWT\BeforeValidException $e) {  // 签名在某个时间点之后才能用
            return_ajax('999999', '签名还不能用!', $e->getMessage());
        } catch (\Firebase\JWT\ExpiredException $e) {  // token过期
            return_ajax('666666', 'token过期!', $e->getMessage());
        } catch (\Exception $e) {  //其他错误
            dump($e->getMessage());
            die;
            return_ajax('999999', '服务器故障!!', $e->getMessage());
        }
    }

    //签发Token
    public static function signToken($id, $username, $mobile)
    {
        $time = time(); //当前时间
        $token = [
            'iat' => $time, //签发时间
//            'nbf' => $time + 30, //(Not Before)：某个时间点后才能访问，比如设置time+30，表示当前时间30秒后才能使用
            'exp' => $time + 604800, //过期时间,这里设置一周
            'data' => [ //自定义信息，不要定义敏感信息
                'uid' => $id,
                'username' => $username,
                'mobile' => $mobile,
            ]
        ];
        $jwt = JWT::encode($token, env('redis_jwt_key'), "HS256");

        $flags = redis()->set('userInfo:'.$id, json_encode($token['data']));

        if (!empty($flags)) {
            return $jwt;
        } else {
            return_ajax('999999', '登录失败');
        }
    }


}

